<!DOCTYPE html>
<html>
<head>
<script src="../../resources/js-test.js"></script>
</head>
<body>
<div>This verifies File.size (for a file from FileSystem API) always returns the fresh size even after the file is modified.</div>
<div id='console'></div>
<script>

if (window.testRunner) {
    testRunner.dumpAsText();
    testRunner.waitUntilDone();
}

var fileEntryForCleanup;
var testFile;
var testText1 = '1234567890';
var testText2 = 'abcdefghijklmnopqrstuvwxyz';

webkitRequestFileSystem(
    window.TEMPORARY, 100, function(fs) {
        fs.root.getFile('test', {create:true}, function(entry) {
            fileEntryForCleanup = entry;
            writeTextToFile(entry, testText1, function() {
                log('Write succeeded.');
                entry.file(onWrittenFile.bind(this, entry), onError);
            });
        }, onError);
    }, onError);

function onWrittenFile(entry, file) {
    testFile = file;
    shouldBe('testFile.size', 'testText1.length');
    // Write into this file again.
    writeTextToFile(entry, testText2, function() {
        log('Write succeeded.');
        entry.file(function(newFile) {
            // The file size should be updated only for the new file.
            shouldBe('testFile.size', 'testText1.length');
            testFile = newFile;
            shouldBe('testFile.size', 'testText2.length');
            cleanup();
        }, onError);
    });
}

function writeTextToFile(entry, contents, successCallback)
{
    log('Writing ' + contents + ' to the file...');
    entry.createWriter(function(writer) {
        log('Created a writer.');
        writer.write(new Blob([contents], {type:'text/plain'}));
        writer.onwriteend = successCallback;
        writer.onerror = onError;
    });
}

function log(text)
{
    var console = document.getElementById('console');
    console.appendChild(document.createTextNode(text));
    console.appendChild(document.createElement('br'));
}

function onError(e)
{
    log('ERROR: ' + e.name);
    console.log(e);
    cleanup();
}

function cleanup()
{
    if (fileEntryForCleanup) {
        fileEntryForCleanup.remove(endTest, endTest);
        return;
    }
    endTest();
}

function endTest()
{
    if (window.testRunner)
        testRunner.notifyDone();
}

</script>
</body>
</html>
